<template>
    <div class="handle-workorder app-container">

      <!-- 搜索过滤栏 -->
      <!--<div class="search el-col-10">-->
      <div class="menu el-col-14">
        <el-button type="default" v-if="showMe?true:false" @click="allItems">全部</el-button>
        <el-button type="default" v-if="showMe?false:true" @click="meItems">与我相关</el-button>
        <el-date-picker v-show="showDate"
                        v-model="dateValue"
                        type="datetimerange"
                        range-separator="-"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :default-time="['09:00:00', '18:00:00']"
                        @change="changeDate">
        </el-date-picker>
        <el-button type="default" v-if="showDate?false:true" @click="showDate=!showDate">过滤时间</el-button>
        <el-button type="default" v-if="showDate?true:false" @click="showDate=!showDate">取消</el-button>
      </div>
      <div class="search el-col-10">
        <el-input  class="input-with-select"
                   placeholder="搜索关键字，id、工单标题."
                   v-model="params.search"
                   @keyup.enter.native="fetchData(params)">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>

      <!-- 处理和待处理的工单列表 -->
      <workorder-table :is-loading="isLoading"
                       :data-list="dataList"
                       :history="history"
                       :status="status"
                       @cancel="cancelWorkorder"
                       @accept="acceptWorkorder"
                       @handle="handleWorkorder">
      </workorder-table>

      <!-- 分页 -->
      <div class="pageination" v-show="total>5">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-sizes="[5, 10, 15, 20]"
          :current-page.sync="params.page"
          :page-size="params.page_size"
          :total="total">
        </el-pagination>
      </div>

      <el-dialog title="处理回复" :visible.sync="handleDialogVisible" width="70%">
        <el-alert title="请输入工单处理回复，兼容Markdown语法，粘贴截图自动上传."
                  show-icon type="info" :closable="false" style="margin-bottom: 10px"></el-alert>
        <el-form :model="workOrder" ref="workOrderForm" :rules="rules">
          <el-form-item prop="result_desc">
            <markdown-editor v-model="workOrder.result_desc"
                             :highlight="true"
                             preview-class="markdown-body"
                             ref="markdownEditor">
            </markdown-editor>
          </el-form-item>
          <el-form-item class="btn-right">
            <el-button type="default" size="small" @click="resetForm">关闭</el-button>
            <el-button type="primary" size="small" @click="handleSubmitWorkOrder">结单</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

    </div>
</template>

<script>
  import { getWorkOrderList, updateWorkOrder, uploadImageFile } from '@/api/workorder'
  import WorkorderTable from '../components/table'
  import { mapGetters } from 'vuex'

  import markdownEditor from 'vue-simplemde/src/markdown-editor'
  import 'simplemde/dist/simplemde.min.css'
  import 'font-awesome/css/font-awesome.min.css'
  import 'github-markdown-css'
  import hljs from 'highlight.js'
  import 'highlight.js/styles/atom-one-light.css'

  window.hljs = hljs
  export default {
    computed: {
      ...mapGetters({
        userid: 'userid'
      })
    },
    components: {
      WorkorderTable,
      markdownEditor
      // vueSimpleMDE
    },
    name: 'handle-workorder',
    data() {
      return {
        handleDialogVisible: false,
        showDate: false,
        showMe: false,
        isLoading: false,
        history: false,
        dataList: [],
        dateValue: '',
        params: {
          page: 1,
          page_size: 10,
          search: '',
          daterange: '',
          user: '',
          status: 1 // status参数值为1返回处理中和刚提交为处理的条目
        },
        total: 0,
        status: [
          { value: 0, text: '待处理', color: 'info' },
          { value: 1, text: '处理中', color: 'primary' }
        ],
        workOrder: {
          result_desc: ''
        },
        rules: {
          result_desc: [{ required: true, message: '请输入处理回复', trigger: 'blur' }]
        }
      }
    },
    created() {
      this.fetchData(this.params)
    },
    methods: {
      // 改变页码和页面大小时获取对应的数据
      handleCurrentChange(val) {
        this.params.page = val
        this.fetchData()
      },
      handleSizeChange(val) {
        this.params.page_size = val
        this.fetchData()
      },
      changeDate() {
        if (this.dateValue) {
          this.params.daterange = `${this.dateValue[0]},${this.dateValue[1]}`
          this.fetchData(this.params)
        }
      },
      meItems() {
        this.showMe = true
        this.fetchData({
          page: 1,
          page_size: 10,
          search: '',
          daterange: '',
          status: 1,
          user: this.userid
        })
      },
      allItems() {
        this.showMe = false
        this.fetchData({
          page: 1,
          page_size: 10,
          search: '',
          daterange: '',
          status: 1,
          user: ''
        })
      },
      fetchData(params) {
        this.isLoading = true
        getWorkOrderList(params).then(
          res => {
            this.isLoading = true
            this.dataList = res.results
            this.total = res.count
          }).catch(
          () => {
            this.isLoading = false
            this.$message.error('获取数据失败')
          })
      },
      searchClick() {},
      cancelWorkorder(row) {
        this.$confirm(`确认取消工单：${row.title} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(
          () => {
            updateWorkOrder(row.id, { status: 3 }).then(() => {
              this.$message.success('工单已取消')
              this.fetchData(this.params)
            }).catch(() => {
              this.$message.error('工单取消失败')
            })
          }).catch(() => {
          this.$message.info('已取消操作')
        })
      },
      acceptWorkorder(row) {
        updateWorkOrder(row.id, { status: 1 }).then(() => {
          this.$message.success('您已接收该工单，请及时处理')
          this.fetchData(this.params)
        }).catch(() => {
          this.$message.error('接收工单失败')
        })
      },
      resetForm() {
        this.handleDialogVisible = false
        // this.workOrder.result_desc = ''
        // this.$refs['workOrderForm'].resetFields()
      },
      handleWorkorder(row) {
        this.workOrder = { ...row }
        this.editCopyImage()
        this.handleDialogVisible = true
      },
      handleSubmitWorkOrder() {
        this.$refs['workOrderForm'].validate(
          (valid) => {
            if (!valid) {
              return
            }
            const id = this.workOrder.id
            const result_desc = this.workOrder.result_desc
            updateWorkOrder(id, { result_desc: result_desc, status: 2 }).then(() => {
              this.resetForm()
              this.$message.success('已回复该工单')
              this.fetchData(this.params)
            }).catch(() => {
              this.resetForm()
              this.$message.error('提交回复失败')
            })
          })
      },
      editCopyImage() {
        this.$nextTick(() => {
          [this.$refs.markdownEditor].map(({ simplemde }) => { // 一共有三个编辑窗口，所以需要循环监听事件
            simplemde.codemirror.on('drop', (editor, e) => { // 拖拽图片的触发函数
              if (!(e.dataTransfer && e.dataTransfer.files)) {
                this.$message({
                  message: '该浏览器不支持操作',
                  type: 'error'
                })
                return
              }
              const dataList = e.dataTransfer.files
              const imageFiles = []
              for (let i = 0; i < dataList.length; i++) {
                if (dataList[i].type.indexOf('image') === -1) {
                  this.$message({
                    message: '仅支持图片拖拽',
                    type: 'error'
                  })
                  continue
                }
                imageFiles.push(dataList[i])
              }
              // this.uploadImagesFile(simplemde.codemirror, imageFiles)
              this.uploadImagesFile(simplemde.codemirror, dataList[0])
              e.preventDefault()
            })
            simplemde.codemirror.on('paste', (editor, e) => { // 粘贴图片的触发函数
              if (!(e.clipboardData && e.clipboardData.items)) {
                this.$message.error('该浏览器不支持操作')
                return
              }
              try {
                const dataList = e.clipboardData.items
                if (dataList[0].kind === 'file' && dataList[0].getAsFile().type.indexOf('image') !== -1) {
                  this.uploadImagesFile(simplemde.codemirror, dataList[0].getAsFile())
                  e.preventDefault() // 若粘贴图片则组织默认粘贴事件发生，若不是图片，触发默认事件
                }
              } catch (e) {
                this.$message.error('请确定你粘贴板是图片，而不是文件')
              }
            })
          })
        })
      },
      uploadImagesFile(simplemde, files) {
        const formData = new FormData()
        formData.append('file', files, files.name)
        uploadImageFile(files.name, formData).then(resps => {
          const { state, data } = resps
          if (!state) { // 如果不是图片文件，则跳过
            this.$message.error(data)
          }
          const url = `![](${location.origin + data})` // 拼接成markdown
          const content = simplemde.getValue()
          simplemde.setValue(content + url + '\n') // 和编辑框之前的内容进行拼接
        }).catch(() => {
          this.$message.error('上传图片失败')
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.handle-workorder {
  .btn-right {
    text-align: right;
  }
}
</style>
